/*
 * Copyright 2010 Christopher Z. Collier
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.xorf.caveman.gui;

import java.awt.event.ActionEvent;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

import javax.swing.AbstractAction;
import javax.swing.SwingWorker;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class WorkerThreadAction extends AbstractAction {
	private static final Logger log = LoggerFactory.getLogger(WorkerThreadAction.class);
    static URLClassLoader classLoader;
    
    //TODO: below static initializer code is temporary.  testing out ability to
    //have a different classloader for worker threads that will know about driver
    //jars.
    static {
		try {
	    	URL url = new URL("file:///home/ccollier/dev/projects/drivers-tmp/hsqldb.jar");
			File jarFile = new File(url.getFile());
			log.info(String.format("file: %s exists: %s", jarFile, jarFile.exists()));
			classLoader = URLClassLoader.newInstance(new URL[] { url });
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
    
	private final class ActionWorker extends SwingWorker<Void, Void> {
		
		@Override
		protected final Void doInBackground() throws Exception {
			Thread currThread = Thread.currentThread();
			
			if (currThread.getContextClassLoader() != classLoader) {
				Thread.currentThread().setContextClassLoader(classLoader);
			}
			
			WorkerThreadAction.this.doOnWorkerThread();
			return (Void) null;
		}
		
		@Override
		protected final void done() {
			WorkerThreadAction.this.after();
		}
	}
	
	public abstract void before();
	public abstract void doOnWorkerThread();
	public abstract void after();
	
	public final void actionPerformed(ActionEvent event) {
		before();
		this.new ActionWorker().execute();
	}
}
